const { name } = require('./package');
const path = require('path');
const fs = require('fs');
const {
  override,
  addLessLoader,
  addWebpackModuleRule,
  overrideDevServer,
  addWebpackAlias,
} = require('customize-cra');

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);

const devServerConfig = () => (config) => {
  config.headers = {
    'Access-Control-Allow-Origin': '*',
  };
  config.historyApiFallback = true;
  config.hot = false;
  // config.watchContentBase = false;
  config.liveReload = false;

  return {
    ...config,
    // compress: true,
    proxy: {
      '/api': {
        target: 'http://localhost:12306/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '',
        },
      },
    },
  };
};

const addCustomqk = () => (config) => {
  config.output.library = `${name}-[name]`;
  config.output.libraryTarget = 'umd';
  // config.output.jsonpFunction = `webpackJsonp_${name}`;
  config.output.globalObject = 'window';

  return config;
};

module.exports = {
  webpack: override(
    // addLessLoader({
    //   lessOptions: {
    //     javascriptEnabled: true,
    //     localIdentName: '[local]--[hash:base64:5]'
    //     // modifyVars: { '@primary-color': '#A80000' },
    //   },
    // }),
    addWebpackModuleRule({
      test: [/\.css$/, /\.less$/],
      use: [
        'style-loader',
        'css-loader',
        'postcss-loader',
        {
          loader: 'less-loader',
          options: {
            lessOptions: {
              strictMath: false,
              noIeCompat: true,
              modifyVars: {
                // "primary-color": "#fcbf2c", // for example, you use Ant Design to change theme color.
              },
              javascriptEnabled: true,
            },
          },
        },
      ],
    }),
    addWebpackAlias({
      '@': resolveApp('src'),
    }),
    addCustomqk()
  ),

  devServer: overrideDevServer(devServerConfig()),
};
